package com.hmall.search.task;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hmall.common.pojo.Item;
import com.hmall.search.service.impl.SearchService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Component
public class PreheatTask {
    private final SearchService searchService;
    private final StringRedisTemplate stringRedisTemplate;

    @Scheduled(cron = "0 0 3 * * ? ") //每天凌晨3点执行一次

    public void preheatItem(){
        LambdaQueryWrapper<Item> wrapper = Wrappers.<Item>lambdaQuery()
                .orderByDesc(Item::getSold)
                .eq(Item::getStatus,1);
        List<Item> itemList = searchService.list(wrapper).stream().limit(20).collect(Collectors.toList());
        String jsonStr = JSONUtil.toJsonStr(itemList);
        stringRedisTemplate.opsForValue().set("hot:item:top20",jsonStr);
    }
}
